<template>
    <div v-loading="loading">
        <div class="btn-list">
            <el-button color="#f06423" @click="goPage(`/console/course/${courseId}/unit/create`)">{{ $t('course.resource_edit.btn_text_1') }}</el-button>
            <el-button color="#f06423" @click="router.go(-1)">{{ $t('golbal.btn_text_3') }}</el-button>
        </div>
        <el-collapse accordion>
            <div ref="collapseRefs">
                <el-collapse-item :name="unitInfo.id" icon="CaretRight" v-for="(unitInfo, index) in unitList" :key="unitInfo.id">
                    <template #title>
                        <div class="unit-tit">
                            <div class="pic">
                                <img :src="unitInfo.icon_url" class="ele" />
                            </div>
                            <h5 class="title">{{ locale === 'en' ? unitInfo.title_en : unitInfo.title_cn }}</h5>
                        </div>
                        <div class="resources-num">
                            <span v-for="item in getResourceInfo(unitInfo._resources)" :key="item.text">{{ $t(item.text) }}: {{ item.count }}</span>
                        </div>
                    </template>
                    <div class="unit-info">
                        <div class="condition-operate">
                            <div class="condition-box">
                                <!-- <el-tag type="primary" effect="dark">受限制的</el-tag>
                                <span>自 2025年5月26日 11:16:14</span> -->
                            </div>
                            <div class="operate-box">
                                <el-button color="#f06423" @click="delUnit(unitInfo)" icon="Delete">{{ $t('course.resource_edit.btn_text_2') }}</el-button>
                                <el-button color="#f06423" @click="goPage(`/console/course/${courseId}/unit/${unitInfo.id}/edit`)" icon="Edit">{{ $t('course.resource_edit.btn_text_3') }}</el-button>
                                <el-button color="#f06423" @click="addResource(unitInfo)" icon="Plus">{{ $t('course.resource_edit.btn_text_4') }}</el-button>
                            </div>
                        </div>
                        <div class="activity-list" v-for="(resources, type) in unitInfo._resources" :key="type">
                            <h5 class="type-tit">{{ $t(imgMap[type].type) }}</h5>
                            <div class="list" :class="`list-${index}`" :ref="el => setListRef(el, type, index)">
                                <div class="activity-item" v-for="item in resources" :key="item.id" :class="`${type}-type`">
                                    <div class="item-box">
                                        <div class="activity-type">{{ $t(imgMap[type].type) }}</div>
                                        <h4 class="activity-tit">{{ item.title }}</h4>
                                        <img :src="imgMap[type].img" :alt="$t(imgMap[type].type)" />

                                        <div class="tools-box">
                                            <el-icon size="16" color="#4c4c4c" @click="editResourceHandle(item, unitInfo)"><Edit /></el-icon>
                                            <el-icon size="16" color="#4c4c4c" @click="delResourceHandle(item, unitInfo)"><Delete /></el-icon>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-collapse-item>
            </div>
        </el-collapse>

        <el-dialog v-model="addResourceDialog" title="新增活動或資源" width="800" @close="cancelAddDialog" class="mobile-dialog">
            <el-form :model="resourceData" label-position="top" v-loading="addResourceDialogLoading">
                <el-form-item :label="$t('course.resource_edit.add_dialog.label_1')">
                    <div class="resource-type-list">
                        <template v-if="!checkedResourceId">
                            <el-card v-for="item in resourceTypeList" :key="item.id" :shadow="resourceData.type === item.id ? 'always' : 'hover'" @click="resourceTypeChangeHandle(item.id)">
                                <el-icon size="18" color="#4c4c4c"><component :is="item.icon" /></el-icon>
                                <span>{{ item.name }}</span>
                            </el-card>
                        </template>
                        <template v-else>
                            <template v-for="item in resourceTypeList" :key="item.id">
                                <el-card v-if="checkedResourceType === item.id" :shadow="resourceData.type === item.id ? 'always' : 'hover'" @click="resourceTypeChangeHandle(item.id)">
                                    <el-icon size="18" color="#4c4c4c"><component :is="item.icon" /></el-icon>
                                    <span>{{ item.name }}</span>
                                </el-card>
                            </template>
                        </template>
                    </div>
                </el-form-item>
                <el-form-item :label="$t('course.resource_edit.add_dialog.label_2')" size="large">
                    <el-input v-model="resourceData.title" :placeholder="$t('course.resource_edit.add_dialog.label_2_placeholder')" />
                </el-form-item>
                <el-form-item :label="$t('course.resource_edit.add_dialog.label_3')" size="large">
                    <RichTextEditor v-model="resourceData.description" @update-richValue="resourceData.description = $event" />
                </el-form-item>
                <template v-if="resourceData.type === 'video'">
                    <el-form-item :label="$t('course.resource_edit.add_dialog.label_4')">
                        <!--<el-upload :show-file-list="false" :before-upload="befoeVideoUpload" accept="video/mp4" :http-request="handleVideoUpload">
                            <el-button color="#f06423" :loading="videoLoading">{{ $t('course.resource_edit.add_dialog.label_4_btn') }}</el-button>
                            <template #tip>
                                <p>{{ $t('course.resource_edit.add_dialog.label_4_placeholder') }}</p>
                            </template>
                        </el-upload>
                        <p v-if="resourceData.video_url">
                            <el-icon size="16" color="#4c4c4c"><VideoPlay /></el-icon>
                            <span>{{ resourceData.video_url.split('/').pop() }}</span>
                        </p>-->
                        <uploadVideo
                            style="width: 100%"
                            ref="uploadVideoRef"
                            @relVideUrl="relVideUrl"
                            :videoUrl="resourceData.video_url"
                            :videoId="checkedResourceId"
                            :panopto_video_id="resourceData.panopto_video_id"
                        />
                    </el-form-item>
                    <!-- <el-form-item :label="$t('course.resource_edit.add_dialog.label_5')"> <el-switch v-model="resourceData.allow_fast_forward" :active-value="1" :inactive-value="0" /> </el-form-item> -->
                </template>
                <el-form-item :label="$t('course.resource_edit.add_dialog.label_6')" v-if="resourceData.type === 'folder'">
                    <div class="btn-list">
                        <el-button color="#f06423" @click="createFolderDialog = true" icon="FolderAdd">{{ $t('course.resource_edit.add_dialog.label_6_btn_1') }}</el-button>
                        <el-button color="#f06423" @click="createDocumentDialog = true" icon="DocumentAdd">{{ $t('course.resource_edit.add_dialog.label_6_btn_2') }}</el-button>
                    </div>
                    <el-tree v-if="resourceData.folderTree.length" :data="resourceData.folderTree" node-key="id" default-expand-all :expand-on-click-node="false" :props="defaultProps">
                        <template #default="{ node, data }">
                            <div class="custom-tree-node">
                                <div v-if="data.resource_type === 'folder'" class="a-box" :class="`${data.resource_type === 'folder' ? 'folder' : data.file_type}-box`">
                                    <el-icon><component :is="data.resource_type === 'folder' ? typeMap['folder'] : typeMap[data.file_type]" /></el-icon>
                                    <span class="tit">{{ data.title }}</span>
                                </div>
                                <a :href="data.file_url" v-else class="a-box" :class="`${data.file_type}-box`">
                                    <el-icon><component :is="data.resource_type === 'folder' ? typeMap['folder'] : typeMap[data.file_type] || 'QuestionFilled'" /></el-icon>
                                    <span class="tit">{{ data.title }}</span>
                                </a>
                                <div class="tools-box">
                                    <el-button
                                        circle
                                        v-if="data.resource_type === 'folder'"
                                        @click="addFolder(data.id)"
                                        icon="FolderAdd"
                                        title="$t('course.resource_edit.add_dialog.label_6_btn_1')"
                                    ></el-button>
                                    <el-button
                                        circle
                                        v-if="data.resource_type === 'folder'"
                                        @click="addDocument(data.id)"
                                        icon="DocumentAdd"
                                        title="$t('course.resource_edit.add_dialog.label_6_btn_2')"
                                    ></el-button>
                                    <el-button circle @click="delDocument(data.id)" icon="Delete" :title="$t('golbal.btn_text_6')"></el-button>
                                </div>
                            </div>
                        </template>
                    </el-tree>
                </el-form-item>
                <template v-if="resourceData.type === 'quiz'">
                    <el-form-item :label="$t('course.resource_edit.add_dialog.label_7')">
                        <el-tree-select
                            :placeholder="$t('course.resource_edit.add_dialog.label_7_placeholder')"
                            v-model="resourceData.quiz_category_id"
                            :data="questionCateList"
                            :render-after-expand="false"
                            :props="quizProps"
                            node-key="id"
                            clearable
                        />
                    </el-form-item>
                    <el-form-item :label="$t('course.resource_edit.add_dialog.label_8')">
                        <el-input v-model="resourceData.question_num" :max="40" />
                    </el-form-item>
                    <el-form-item :label="$t('course.resource_edit.add_dialog.label_9')">
                        <el-input v-model="resourceData.pass_score" :min="0" />
                    </el-form-item>
                    <el-form-item :label="$t('course.resource_edit.add_dialog.label_10')">
                        <el-input v-model="resourceData.total_score" :min="0" />
                    </el-form-item>
                </template>
                <template v-if="resourceData.type === 'file'">
                    <el-form-item :label="$t('course.resource_edit.add_dialog.label_11')">
                        <el-upload :show-file-list="false" :before-upload="beforeDocumentUpload" :http-request="handleDocumentUpload">
                            <el-button color="#f06423" :loading="documentLoading">{{ $t('course.resource_edit.add_dialog.label_11_btn') }}</el-button>
                            <template #tip>
                                <p>{{ $t('course.resource_edit.add_dialog.label_22_placeholder') }}</p>
                            </template>
                        </el-upload>
                        <p v-if="resourceData.document_url">
                            <el-icon size="16" color="#4c4c4c"><Document /></el-icon>
                            <span>{{ resourceData.document_url.split('/').pop() }}</span>
                        </p>
                    </el-form-item>
                    <el-form-item :label="$t('course.resource_edit.add_dialog.label_12')"> <el-switch v-model="resourceData.is_required" /> </el-form-item>
                </template>
                <template v-if="resourceData.type === 'report'">
                    <!-- <el-form-item :label="$t('course.resource_edit.add_dialog.label_13')"> <el-switch v-model="resourceData.is_hidden" /> </el-form-item> -->
                    <!-- <el-form-item :label="$t('course.resource_edit.add_dialog.label_14')">
                        <el-date-picker v-model="resourceData.start_date" type="date" :placeholder="$t('course.resource_edit.add_dialog.label_14_placeholder')" />
                    </el-form-item>
                    <el-form-item :label="$t('course.resource_edit.add_dialog.label_15')">
                        <el-date-picker v-model="resourceData.end_date" type="date" :placeholder="$t('course.resource_edit.add_dialog.label_15_placeholder')" />
                    </el-form-item> -->
                    <el-form-item :label="$t('course.resource_edit.add_dialog.label_16')">
                        <el-input v-model="resourceData.total_score" :min="0" :placeholder="$t('course.resource_edit.add_dialog.label_16_placeholder')" />
                    </el-form-item>
                </template>
            </el-form>
            <template #footer>
                <el-button color="#F06423" @click="addResourceHandle" :loading="addResourceDialogBtnLoading">存儲变更</el-button>
                <el-button @click="cancelAddDialog" color="#435764" :loading="addResourceDialogBtnLoading">取消</el-button>
            </template>
        </el-dialog>

        <el-dialog v-model="createFolderDialog" :title="$t('course.resource_edit.create_folder_dialog.tit')" width="400" class="mobile-dialog">
            <el-input v-model="createFolderName" :placeholder="$t('course.resource_edit.create_folder_dialog.placeholder')">
                <template #prepend>{{ $t('course.resource_edit.create_folder_dialog.label') }}</template>
            </el-input>
            <template #footer>
                <el-button color="#F06423" @click="createFolder">{{ $t('golbal.btn_text_4') }}</el-button>
                <el-button @click="createFolderDialog = false" color="#435764">{{ $t('golbal.btn_text_3') }}</el-button>
            </template>
        </el-dialog>

        <el-dialog v-model="createDocumentDialog" :title="$t('course.resource_edit.create_document_dialog.tit')" width="400" class="mobile-dialog">
            <el-upload drag multiple :before-upload="beforeFolderUpload" :http-request="handleFolderUpload" v-model:file-list="upDocumentList">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    {{ $t('course.resource_edit.create_document_dialog.tip_1') }} <em>{{ $t('course.resource_edit.create_document_dialog.tip_2') }}</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">{{ $t('course.resource_edit.create_document_dialog.tip_3') }}</div>
                </template>
            </el-upload>
            <template #footer>
                <el-button color="#F06423" @click="createDocument">{{ $t('golbal.btn_text_4') }}</el-button>
                <el-button @click="createDocumentDialog = false" color="#435764">{{ $t('golbal.btn_text_3') }}</el-button>
            </template>
        </el-dialog>

        <el-dialog v-model="delResourceDialog" :title="$t('course.resource_edit.del_resource_dialog.tit')" width="400" class="mobile-dialog">
            <p>{{ $t('course.resource_edit.del_resource_dialog.con') }}</p>
            <template #footer>
                <el-button color="#F06423" @click="confirmDelResource" :loading="delResourceDialogLoading">{{ $t('golbal.btn_text_4') }}</el-button>
                <el-button @click="delResourceDialog = false" color="#435764">{{ $t('golbal.btn_text_3') }}</el-button>
            </template>
        </el-dialog>

        <el-dialog v-model="delUnitDialog" :title="$t('course.resource_edit.del_resource_dialog.tit')" width="400" class="mobile-dialog">
            <p>{{ $t('course.resource_edit.del_resource_dialog.con') }}</p>
            <template #footer>
                <el-button color="#F06423" @click="confirmDelUnit" :loading="delUnitDialogLoading">{{ $t('golbal.btn_text_4') }}</el-button>
                <el-button @click="delUnitDialog = false" color="#435764">{{ $t('golbal.btn_text_3') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import RichTextEditor from '@/components/RichTextEditor.vue'

import UnitService from '@/api/unit'
import type { UnitItem } from '@/types/unit'

import ResourceService from '@/api/resource'
import type { FolderInfo, ResourceItem } from '@/types/resource'

import QuestionService from '@/api/question'
import type { CateItem } from '@/types/question'

import QuizService from '@/api/quiz'
import AssignService from '@/api/assign'

import VideoImg from '@/assets/img/video-1.svg'
import FolderImg from '@/assets/img/folder-1.svg'
import QuizImg from '@/assets/img/quiz-1.svg'
import AssignImg from '@/assets/img/assign-1.svg'
import FileImg from '@/assets/img/file-1.svg'

import { goPage } from '@/utils/global'
import { ElMessage, type UploadRequestOptions } from 'element-plus'

import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

import Sortable from 'sortablejs'
const uploadVideoRef = ref<any>(null)
const route = useRoute()
const router = useRouter()
const courseId = computed(() => Number(route.params.courseId))
const { locale, t } = useI18n<{ message: MessageSchema }, SupportedLocales>()
const loading = ref(false)
const collapseRefs = ref<HTMLElement>()
const collapseSortable = ref<Sortable>()
const listRefs = ref<any>({})
const listSortables = ref<Sortable[]>([])
const imgMap: any = {
    video: {
        type: 'course.resource_edit.resource_type_1',
        img: VideoImg,
        get: () => {
            ResourceService.videoInfo(checkedResourceId.value)
                .then(res => {
                    resourceData.value = {
                        id: res.id,
                        type: 'video',
                        title: res.title,
                        description: res.description || '',
                        video_url: res.video_url,
                        panopto_video_id: res.panopto_video_id,
                        duration: res.duration,
                        document_url: '',
                        file_type: 'video',
                        folderTree: [],
                        quiz_category_id: null as number | null,
                        allow_fast_forward: res.allow_fast_forward,
                        is_required: false,
                        resource_type: 'video',
                        question_num: 10,
                        pass_score: '0',
                        total_score: '100.00',
                    }
                })
                .finally(() => {
                    addResourceDialogLoading.value = false
                })
        },
        set: () => {
            let data: any = {
                course_id: courseId.value,
                unit_id: checkedUnit.value?.id,
                title: resourceData.value.title,
                description: resourceData.value.description || '',
                video_url: resourceData.value.video_url,
                panopto_video_id: resourceData.value.panopto_video_id,
                duration: resourceData.value.duration,
                allow_fast_forward: resourceData.value.allow_fast_forward,
            }
            if (resourceData.value.id) data.id = resourceData.value.id

            ResourceService.videoSave(data)
                .then(() => {
                    getUnitList()
                    getQuestionCateList()
                    addResourceDialog.value = false
                })
                .finally(() => {
                    addResourceDialogBtnLoading.value = false
                })
        },
    },
    folder: {
        type: 'course.resource_edit.resource_type_2',
        img: FolderImg,
        get: () => {
            ResourceService.folderInfo(checkedResourceId.value)
                .then(res => {
                    resourceData.value = {
                        id: res.id,
                        type: 'folder',
                        title: res.title,
                        description: res.description || '',
                        video_url: '',
                        panopto_video_id: 0,
                        duration: 0,
                        document_url: '',
                        file_type: res.file_type,
                        folderTree: reactive(res.children ?? []),
                        quiz_category_id: null as number | null,
                        allow_fast_forward: 0,
                        is_required: res.is_required,
                        resource_type: 'folder',
                        question_num: 10,
                        pass_score: '0',
                        total_score: '100.00',
                    }
                    console.log(123, resourceData.value.folderTree)
                })
                .finally(() => {
                    addResourceDialogLoading.value = false
                })
        },
        set: () => {
            // 递归移除id的方法
            const removeIds = (nodes: any[]): any[] => {
                return nodes.map(({ children, tree_id, is_required, ...rest }) => {
                    if (rest.resource_type === 'folder') {
                        delete rest.file_url
                    }
                    return {
                        ...rest,
                        ...(children?.length && { children: removeIds(children) }),
                    }
                })
            }

            let data: any = {
                course_id: courseId.value,
                unit_id: checkedUnit.value?.id,
                title: resourceData.value.title,
                description: resourceData.value.description || '',
                resource_type: resourceData.value.resource_type,
                children: removeIds([...resourceData.value.folderTree]),
            }
            if (resourceData.value.id) data.id = resourceData.value.id
            console.log('data', data)
            ResourceService.folderSave(data)
                .then(() => {
                    getUnitList()
                    getQuestionCateList()
                    addResourceDialog.value = false
                })
                .finally(() => {
                    addResourceDialogBtnLoading.value = false
                })
        },
    },
    quiz: {
        type: 'course.resource_edit.resource_type_3',
        img: QuizImg,
        get: () => {
            QuizService.getById(checkedResourceId.value)
                .then(res => {
                    resourceData.value = {
                        id: res.id,
                        type: 'quiz',
                        title: res.title,
                        description: res.description || '',
                        video_url: '',
                        panopto_video_id: 0,
                        duration: 0,
                        document_url: '',
                        folderTree: [],
                        quiz_category_id: res.question_category_id,
                        allow_fast_forward: 0,
                        is_required: false,
                        file_type: 'quiz',
                        resource_type: 'quiz',
                        question_num: 10,
                        pass_score: res.pass_score,
                        total_score: res.total_score,
                    }
                })
                .finally(() => {
                    addResourceDialogLoading.value = false
                })
        },
        set: () => {
            let data: any = {
                unit_id: checkedUnit.value?.id,
                title: resourceData.value.title,
                description: resourceData.value.description || '',
                question_category_id: resourceData.value.quiz_category_id,
                question_num: resourceData.value.question_num,
                type: 'multiple_choice',
                pass_score: resourceData.value.pass_score,
                total_score: resourceData.value.total_score,
            }
            if (resourceData.value.id) data.id = resourceData.value.id

            QuizService.save(data)
                .then(() => {
                    getUnitList()
                    getQuestionCateList()
                    addResourceDialog.value = false
                })
                .finally(() => {
                    addResourceDialogBtnLoading.value = false
                })
        },
    },
    report: {
        type: 'course.resource_edit.resource_type_4',
        img: AssignImg,
        get: () => {
            AssignService.getById(checkedResourceId.value)
                .then(res => {
                    resourceData.value = {
                        id: res.id,
                        type: 'report',
                        title: res.title,
                        description: res.description || '',
                        video_url: '',
                        panopto_video_id: 0,
                        duration: 0,
                        document_url: '',
                        folderTree: [],
                        quiz_category_id: null as number | null,
                        allow_fast_forward: 0,
                        is_required: false,
                        file_type: 'report',
                        resource_type: 'report',
                        question_num: 10,
                        pass_score: '0',
                        total_score: res.total_score,
                    }
                })
                .finally(() => {
                    addResourceDialogLoading.value = false
                })
        },
        set: () => {
            let data: any = {
                course_id: courseId.value,
                unit_id: checkedUnit.value?.id,
                title: resourceData.value.title,
                description: resourceData.value.description || '',
                total_score: resourceData.value.total_score,
            }
            if (resourceData.value.id) data.id = resourceData.value.id

            AssignService.save(data)
                .then(() => {
                    getUnitList()
                    getQuestionCateList()
                    addResourceDialog.value = false
                })
                .finally(() => {
                    addResourceDialogBtnLoading.value = false
                })
        },
    },
    file: {
        type: 'course.resource_edit.resource_type_5',
        img: FileImg,
        get: () => {
            ResourceService.fileInfo(checkedResourceId.value)
                .then(res => {
                    resourceData.value = {
                        id: res.id,
                        type: 'file',
                        title: res.title,
                        description: res.description || '',
                        video_url: '',
                        panopto_video_id: 0,
                        duration: 0,
                        document_url: res.file_url,
                        folderTree: [],
                        quiz_category_id: null as number | null,
                        allow_fast_forward: 0,
                        is_required: false,
                        file_type: 'file',
                        resource_type: 'file',
                        question_num: 10,
                        pass_score: '0',
                        total_score: '100.00',
                    }
                })
                .finally(() => {
                    addResourceDialogLoading.value = false
                })
        },
        set: () => {
            let data: any = {
                course_id: courseId.value,
                unit_id: checkedUnit.value?.id,
                title: resourceData.value.title,
                description: resourceData.value.description || '',
                file_url: resourceData.value.document_url,
                file_type: resourceData.value.file_type,
                is_required: resourceData.value.is_required,
            }
            if (resourceData.value.id) data.id = resourceData.value.id

            ResourceService.fileSave(data)
                .then(() => {
                    getUnitList()
                    getQuestionCateList()
                    addResourceDialog.value = false
                })
                .finally(() => {
                    addResourceDialogBtnLoading.value = false
                })
        },
    },
}
const typeMap: { [key: string]: string } = {
    image: 'Picture',
    video: 'VideoPlay',
    audio: 'Mic',
    pdf: 'Document',
    word: 'Tickets',
    excel: 'PieChart',
    ppt: 'DataAnalysis',
    txt: 'Memo',
    zip: 'Box',
    folder: 'Folder',
    other: 'QuestionFilled',
}

// 单元列表
const unitList = ref<UnitItem[]>([])
const checkedUnit = ref<UnitItem>() // 当前选中单元
const checkedResourceId = ref<number>(0) // 当前选中资源id
const checkedResourceType = ref<string>('video') // 当前选中资源类型
// 初始化sortable

const setListRef = (el: any, type: string | number, index: number) => {
    if (el) {
        const key = String(type)
        if (!listRefs.value[key]) {
            listRefs.value[key] = []
        }
        listRefs.value[key][index] = el
    }
}

function initSortable() {
    nextTick(() => {
        if (collapseRefs.value) {
            if (collapseSortable.value) collapseSortable.value.destroy()
            collapseSortable.value = Sortable.create(collapseRefs.value, {
                handle: '.el-collapse-item__header',
                animation: 150,
                ghostClass: 'sortable-ghost',
                onEnd: (evt: any) => {
                    if (evt.oldIndex !== evt.newIndex) {
                        loading.value = true
                        const newItems = [...unitList.value]
                        const [removed] = newItems.splice(evt.oldIndex, 1)
                        newItems.splice(evt.newIndex, 0, removed)

                        // 单元排序完成后的接口处理
                        UnitService.sort(newItems.map((item, index) => ({ id: item.id, sort_order: index })))
                            .then(() => {
                                unitList.value = newItems
                            })
                            .finally(() => {
                                loading.value = false
                            })
                    }
                },
            })
        }

        if (listSortables.value.length) {
            listSortables.value.forEach((item: Sortable) => item.destroy())
            listSortables.value = []
        }
        if (listRefs.value.video) {
            listRefs.value.video.forEach((el: HTMLElement, index: number) => {
                if (!el) return
                listSortables.value.push(
                    Sortable.create(el, {
                        animation: 150,
                        ghostClass: 'sortable-ghost',
                        onEnd: (evt: any) => {
                            if (evt.oldIndex !== evt.newIndex) {
                                loading.value = true
                                const currentVideos = unitList.value[index]._resources
                                const newVideos = [...currentVideos.video]
                                const [removed] = newVideos.splice(evt.oldIndex, 1)
                                newVideos.splice(evt.newIndex, 0, removed)
                                // 资源排序完成后的接口处理
                                ResourceService.videoSort(newVideos.map((item, index) => ({ id: item.id, sort_order: index })))
                                    .then(() => {
                                        currentVideos.video = newVideos
                                    })
                                    .finally(() => {
                                        loading.value = false
                                    })
                            }
                        },
                    }),
                )
            })
        }

        loading.value = false
    })
}
// 获取单元列表
function getUnitList() {
    loading.value = true
    listRefs.value = {}
    UnitService.list(courseId.value)
        .then(res => {
            unitList.value = res
            initSortable()
        })
        .catch(() => {
            loading.value = false
        })
}
// 计算资源数量
function getResourceInfo(resources: { [key: string]: ResourceItem[] }): { text: string; count: number }[] {
    return Object.keys(resources).map(key => ({
        text: imgMap[key as keyof typeof imgMap].type,
        count: resources[key as keyof typeof resources].length,
    }))
}
// 删除单元(弹窗)
const delUnit = (unitInfo: UnitItem) => {
    checkedUnit.value = unitInfo
    delUnitDialog.value = true
}
// 新增资源(弹窗)
const addResource = (unitInfo: UnitItem) => {
    checkedResourceType.value = 'video'
    checkedResourceId.value = 0
    checkedUnit.value = unitInfo
    resourceData.value = {
        id: 0,
        type: 'video',
        title: '',
        description: '',
        video_url: '',
        panopto_video_id: 0,
        duration: 0,
        allow_fast_forward: 0,
        document_url: '',
        file_type: 'other',
        folderTree: reactive<FolderInfo[]>([]),
        quiz_category_id: null as number | null,
        resource_type: 'video',
        is_required: false,
        question_num: 10,
        pass_score: '0',
        total_score: '100.00',
    }
    addResourceDialog.value = true
}
// 编辑资源(弹窗)
const editResourceHandle = (resources: ResourceItem, unitInfo: UnitItem) => {
    addResourceDialogLoading.value = true
    checkedResourceType.value = resources.type
    checkedResourceId.value = resources.id
    checkedUnit.value = unitInfo
    imgMap[resources.type].get()
    addResourceDialog.value = true
}
// 删除资源(弹窗)
const delResourceHandle = ({ id, type }: ResourceItem, unitInfo: UnitItem) => {
    checkedResourceType.value = type
    checkedResourceId.value = id
    checkedUnit.value = unitInfo
    delResourceDialog.value = true
}

// 题库分类列表
const questionCateList = ref<CateItem[]>([])
const quizProps = {
    id: 'id',
    children: 'children',
    label: 'name',
}
// 获取题库分类列表
function getQuestionCateList() {
    QuestionService.cateList().then(res => {
        questionCateList.value = res.items
    })
}

// 新增活动或资源
const addResourceDialog = ref(false) // 新增活动或资源 对话框
const addResourceDialogBtnLoading = ref(false) // 新增活动或资源 对话框按钮loading
const addResourceDialogLoading = ref(false) // 新增活动或资源 对话框loading
// 资源类型列表
const resourceTypeList = ref([
    {
        id: 'video',
        name: t('course.resource_edit.resource_type_1'),
        icon: 'VideoPlay',
    },
    {
        id: 'folder',
        name: t('course.resource_edit.resource_type_2'),
        icon: 'Folder',
    },
    {
        id: 'quiz',
        name: t('course.resource_edit.resource_type_3'),
        icon: 'Tickets',
    },
    {
        id: 'report',
        name: t('course.resource_edit.resource_type_4'),
        icon: 'Reading',
    },
    {
        id: 'file',
        name: t('course.resource_edit.resource_type_5'),
        icon: 'Document',
    },
])
// 资源数据
const resourceData = ref({
    id: 0,
    type: 'video',
    title: '',
    description: '',

    // 视频
    video_url: '',
    panopto_video_id: 0,
    duration: 0,
    allow_fast_forward: 0,

    // 档案
    document_url: '',
    file_type: 'other',
    is_required: false,

    // 资料夹
    folderTree: reactive<FolderInfo[]>([]),
    resource_type: 'folder',

    // 測驗卷
    quiz_category_id: null as number | null,
    question_num: 10,
    pass_score: '0',
    total_score: '100.00',

    // 反思报告
})
const defaultProps = {
    id: 'id',
    children: 'children',
    label: 'title',
}
// 新增资源(确定)
const addResourceHandle = () => {
    addResourceDialogBtnLoading.value = true
    imgMap[checkedResourceType.value].set()
}
// 关闭资源弹窗
const cancelAddDialog = () => {
    if (uploadVideoRef.value) {
        uploadVideoRef.value.resetUpload()
    }
    addResourceDialog.value = false
}
// 资源类型切换
const resourceTypeChangeHandle = (type: string) => {
    checkedResourceType.value = type
    resourceData.value.type = type
    if (type == 'quiz') {
        resourceData.value.total_score = '100.00'
    } else {
        resourceData.value.total_score = '100.00'
    }
}

// 上传视频资源
const videoLoading = ref(false)
const befoeVideoUpload = (file: File) => {
    videoLoading.value = true
    const isMP4 = file.type === 'video/mp4'
    const isLt500M = file.size / 1024 / 1024 < 500

    if (!isMP4) {
        ElMessage.error(`${t('golbal.upload_err_2')} MP4 ${t('golbal.upload_err_3')}`)
        videoLoading.value = false
        return false
    }
    if (!isLt500M) {
        ElMessage.error(`${t('golbal.upload_err_4')} 500MB`)
        videoLoading.value = false
        return false
    }

    return true
}

import uploadVideo from './components/uploadVideo.vue'

const handleVideoUpload = (options: UploadRequestOptions) => {
    const { file } = options
    const data = new FormData()
    data.append('file', file)
    data.append('type', 'video')
    data.append('filename', file.name)
    ResourceService.upload(data)
        .then(res => {
            resourceData.value.video_url = res.url
            resourceData.value.duration = res.duration || 0
        })
        .finally(() => {
            videoLoading.value = false
        })
}

// 上传档案资源
const documentLoading = ref(false)
const beforeDocumentUpload = (file: File) => {
    documentLoading.value = true
    const isLt500M = file.size / 1024 / 1024 < 500

    if (!isLt500M) {
        ElMessage.error(`${t('golbal.upload_err_4')} 500MB`)
        documentLoading.value = false
        return false
    }

    return true
}
const handleDocumentUpload = (options: UploadRequestOptions) => {
    const { file } = options
    const data = new FormData()
    data.append('file', file)
    data.append('filename', file.name)
    ResourceService.upload(data)
        .then(res => {
            resourceData.value.document_url = res.url
            resourceData.value.file_type = res.file_type
        })
        .finally(() => {
            documentLoading.value = false
        })
}

// 资料夹
const createFolderDialog = ref(false)
const createFolderName = ref('')
const checkedFolderId = ref<number>(0)
function findFolder(folders: FolderInfo[], parentId: number, info: FolderInfo) {
    for (let i = 0; i < folders.length; i++) {
        if (folders[i].id === parentId) {
            folders[i].children?.push(info)
        }
        if (folders[i].children?.length) {
            findFolder(folders[i].children ?? reactive<FolderInfo[]>([]), parentId, info)
        }
    }
}
const createFolder = () => {
    const info = reactive({
        id: Date.now(),
        title: createFolderName.value,
        description: '',
        resource_type: 'folder',
        sort_order: 0,
        file_url: '',
        file_type: 'other',
        children: reactive<FolderInfo[]>([]),
        unit_id: checkedUnit.value?.id || 0,
        tree_id: checkedFolderId.value,
        is_required: false,
    })
    if (checkedFolderId.value === 0) {
        resourceData.value.folderTree.push(info)
    } else {
        findFolder(resourceData.value.folderTree, checkedFolderId.value, info)
    }
    createFolderDialog.value = false
    createFolderName.value = ''
    checkedFolderId.value = 0
}
const addFolder = (parentId?: number) => {
    createFolderDialog.value = true
    checkedFolderId.value = parentId || 0
}

// 资料夹中的文件
const createDocumentDialog = ref(false)
const createDocumentList = ref<any[]>([])
const upDocumentList = ref<any[]>([])
const addDocument = (parentId?: number) => {
    createDocumentDialog.value = true
    checkedFolderId.value = parentId || 0
}
const createDocument = () => {
    createDocumentList.value.forEach(item => {
        const info = reactive({
            id: 0,
            title: item.name,
            description: '',
            resource_type: 'file',
            sort_order: 0,
            file_url: item.url,
            file_type: item.type,
            unit_id: checkedUnit.value?.id || 0,
            tree_id: checkedFolderId.value,
            is_required: false,
        })
        if (checkedFolderId.value === 0) {
            resourceData.value.folderTree.push(info)
        } else {
            findFolder(resourceData.value.folderTree, checkedFolderId.value, info)
        }
    })
    createDocumentDialog.value = false
    createDocumentList.value = []
    checkedFolderId.value = 0
    upDocumentList.value = []
}
const delDocument = (id: number) => {
    ResourceService.deleteFolder(id)
        .then(res => {
            const removeNode = (nodes: FolderInfo[]): boolean => {
                for (let i = 0; i < nodes.length; i++) {
                    if (nodes[i].id === id) {
                        nodes.splice(i, 1)
                        return true
                    }
                    if (nodes[i].children?.length) {
                        const found = removeNode(nodes[i].children!)
                        if (found) return true
                    }
                }
                return false
            }
            removeNode(resourceData.value.folderTree)
        })
        .finally(() => {})
}
const beforeFolderUpload = (file: File) => {
    const isLt500M = file.size / 1024 / 1024 < 500

    if (!isLt500M) {
        ElMessage.error(`${t('golbal.upload_err_4')} 500MB`)
        return false
    }

    return true
}
const handleFolderUpload = (options: UploadRequestOptions) => {
    const { file } = options
    const data = new FormData()
    data.append('file', file)
    data.append('filename', file.name)
    ResourceService.upload(data).then(res => {
        createDocumentList.value.push({
            name: res.original_name,
            url: res.url,
            type: res.file_type,
        })
    })
}

// 删除资源弹窗
const delResourceDialog = ref(false)
const delResourceDialogLoading = ref(false)
const confirmDelResource = () => {
    delResourceDialogLoading.value = true
    ResourceService.deleteByType(checkedResourceId.value, checkedResourceType.value)
        .then(() => {
            getUnitList()
            delResourceDialog.value = false
        })
        .finally(() => {
            delResourceDialogLoading.value = false
        })
}

// 删除单元弹窗
const delUnitDialog = ref(false)
const delUnitDialogLoading = ref(false)
const confirmDelUnit = () => {
    delUnitDialogLoading.value = true
    UnitService.delete(checkedUnit.value?.id!)
        .then(() => {
            getUnitList()
            delUnitDialog.value = false
        })
        .finally(() => {
            delUnitDialogLoading.value = false
        })
}

onMounted(() => {
    getUnitList()
    getQuestionCateList()
})

//获取上传的url地址
const relVideUrl = ({ url, panopto_video_id }: { url: string; panopto_video_id: number }) => {
    console.log('我是上传后的url：', url)
    resourceData.value.video_url = url
    resourceData.value.panopto_video_id = panopto_video_id
    resourceData.value.duration = 0
}
</script>

<style lang="less" scoped>
@import '@/assets/styles/variable.less';
:deep(.el-collapse) {
    --el-collapse-header-height: auto;
    --el-collapse-header-bg-color: #f0f8f9;

    .el-collapse-item {
        margin-bottom: 45px;

        .el-collapse-item__header {
            border-top: 6px solid #00a9ce;
            border-bottom: none;
            padding: 10px 20px;

            .el-collapse-item__arrow {
                font-size: 24px;
                color: #999;
            }
        }
    }
}

.unit-tit {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 20px;

    .pic {
        width: 100px;
    }

    .title {
        font-size: 24px;
        font-weight: bold;
        line-height: 1.2;
        color: #999;
    }
}

.resources-num {
    display: flex;
    align-items: center;
    gap: 14px;
    color: #999;
}

.unit-info {
    padding: 20px;

    .condition-operate {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .condition-box {
            display: flex;
            align-items: center;
            gap: 10px;
            color: #000;
        }
    }

    .activity-list {
        margin-top: 30px;

        .type-tit {
            margin-bottom: 15px;
            width: 100%;
            font-size: 18px;
            font-weight: bold;
            color: #000;
            line-height: 1.2;
        }

        .list {
            .activity-item {
                cursor: auto;
                width: calc(25% - 11.25px);
                @media screen and (max-width: @lPhone) {
                    width: calc(50% - 11.25px);
                }
                &.video-type {
                    cursor: move;
                }

                .item-box {
                    img {
                        top: 60%;
                    }

                    .tools-box {
                        position: absolute;
                        right: 10px;
                        bottom: 10px;
                        z-index: 2;
                    }
                }
            }
        }
    }
}

.el-form {
    .el-form-item {
        p {
            margin-top: 4px;
            margin-bottom: 10px;
            font-size: 12px;
            color: #4c4c4c;
            line-height: 1.2;
            width: 100%;

            display: flex;
            align-items: center;
            gap: 6px;
        }
    }
}

.resource-type-list {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
    :deep(.el-card) {
        cursor: pointer;
        min-width: 80px;

        .el-card__body {
            padding: 15px;
            font-size: 15px;
            color: #4c4c4c;
            line-height: 1.2;

            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 6px;
        }
    }
}

:deep(.ck-editor) {
    width: 100%;

    .ck-editor__main {
        .ck-content {
            min-height: 200px;
            max-height: 300px;
        }
    }
}

.el-tree {
    width: 100%;
    --el-tree-node-content-height: 40px;

    .custom-tree-node {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-grow: 1;

        .a-box {
            display: flex;
            align-items: center;
            gap: 10px;

            .el-icon {
                color: #b5b5b5;
            }

            .tit {
                color: #000;
            }

            &:hover {
                .tit {
                    color: #242424;
                }
            }

            &.image-box {
                .el-icon {
                    color: #8688cb;
                }
            }
            &.video-box {
                .el-icon {
                    color: #652e2e;
                }
            }
            &.audio-box {
                .el-icon {
                    color: #e5fafc;
                }
            }
            &.pdf-box {
                .el-icon {
                    color: #eb2f3b;
                }
            }
            &.word-box {
                .el-icon {
                    color: #1d70f5;
                }
            }
            &.excel-box {
                .el-icon {
                    color: #069e61;
                }
            }
            &.ppt-box {
                .el-icon {
                    color: #f5670f;
                }
            }
            &.zip-box {
                .el-icon {
                    color: #f4b10a;
                }
            }
            &.folder-box {
                .el-icon {
                    color: #bb9f54;
                }
            }
        }

        .el-button {
            color: #4c4c4c;
        }
    }
}

.tools-box {
    display: flex;
    align-items: center;
    gap: 10px;

    .el-icon {
        cursor: pointer;

        &:hover {
            color: #f06423;
        }
    }
}

.video-player {
    position: fixed;
    width: 1px;
    height: 1px;
    opacity: 0;
    z-index: -99;
}

:deep(.btn-list) {
    margin-bottom: 30px;
    display: flex;
    justify-content: flex-end;
    width: 100%;
}
.operate-box {
    display: flex;
    flex-wrap: wrap;
    row-gap: 10px;
}
</style>
